package model

import (
	"errors"
	"fmt"
	"github.com/bgmp/config"
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"time"
)

const (
	Patient = 0
	Doctor  = 1
)

type User struct {
	gorm.Model
	Username string `json:"username"`
	Avatar   string `json:"avatar"`
	OpenId   string `json:"openId"`
	Role     int    `json:"role"`
	Phone    string `json:"phone"`
}

type UserVO struct {
	ID       uint   `json:"id"`
	Username string `json:"username"`
	Avatar   string `json:"avatar"`
	Phone    string `json:"phone"`
}

func (u *User) Create(db *gorm.DB) error {
	err := db.Create(u).Error
	if err != nil {
		return err
	}
	detail := UserDetail{}
	detail.UserId = u.ID
	detail.Birthday = time.Now()
	return detail.Create(db)
}

func (u *User) Get(db *gorm.DB) error {
	return db.First(u).Error
}

func (u *User) Save(db *gorm.DB) error {
	return db.Save(u).Error
}

func (u *User) Update(db *gorm.DB) error {
	return db.Model(u).Where(Eq("id", u.ID)).Updates(u).Error
}

func (u *User) IsDoctor() bool {
	return u.Role == Doctor
}

func (u *User) GetUserVO() *UserVO {
	return &UserVO{
		ID:       u.ID,
		Username: u.Username,
		Avatar:   u.Avatar,
		Phone:    u.Phone,
	}
}

func (u *User) GetByName(db *gorm.DB) error {
	return db.Where("username = ?", u.Username).Find(u).Error
}

func GetUserByOpenId(openid string) (user *User, err error) {
	log.Info("openid " + openid)
	var users []User
	config.DB.Where("open_id = ?", openid).Find(&users)
	if len(users) == 0 {
		log.Info(fmt.Sprintf("用户 %s 不存在", openid))
		err = errors.New("用户不存在")
		return
	}
	user = &users[0]
	return
}

func GetUserByRole(db *gorm.DB, role int) ([]User, error) {
	var users []User
	err := db.Where(Eq("role", role)).Find(&users).Error
	if err != nil {
		return nil, err
	}
	return users, nil
}

func GetUserIds(db *gorm.DB) ([]uint, error) {
	var ids []uint
	err := db.Table("users").Select("id").Find(&ids).Error
	if err != nil {
		return nil, err
	}
	return ids, nil
}

type UserSelectConditions struct {
	Username string `json:"username"`
	Role     int    `json:"role"`
}

func GetUsersByCondition(db *gorm.DB, condition *UserSelectConditions) ([]User, error) {
	var users []User
	tx := db.Where(Eq("role", condition.Role))
	if condition.Username != "" {
		tx = tx.Where("username LIKE ?", fmt.Sprintf("%%%s%%", condition.Username))
	}
	err := tx.Find(&users).Error
	if err != nil {
		return nil, err
	}
	return users, nil
}
